import { EditorView } from "prosemirror-view";
import { EditorState } from "prosemirror-state";
import {
  schema as baseSchema,
  MarkdownParser,
  MarkdownSerializer,
  defaultMarkdownParser,
  defaultMarkdownSerializer
} from "prosemirror-markdown";
import { exampleSetup } from "prosemirror-example-setup";
import {
  tableEditing,
  columnResizing,
  tableNodes,
  fixTables
} from "prosemirror-tables";
import { Schema, Node } from "prosemirror-model";
import { keymap } from "prosemirror-keymap";

// 创建包含表格节点的schema
const schema = new Schema({
  nodes: baseSchema.spec.nodes.append(
    tableNodes({
      tableGroup: "block",
      cellContent: "block+",
      cellAttributes: {
        background: {
          default: null,
          getFromDOM(dom) {
            return dom.style.backgroundColor || null;
          },
          setDOMAttr(value, attrs) {
            if (value)
              attrs.style = (attrs.style || "") + `background-color: ${value};`;
          }
        }
      }
    })
  ),
  marks: baseSchema.spec.marks
});

// 使用默认解析器进行基础解析（更安全、更兼容）

// 创建扩展的序列化器，支持表格和其他新功能
const markdownSerializer = new MarkdownSerializer(
  // 扩展默认的节点序列化规则
  {
    // 继承默认的序列化规则
    ...defaultMarkdownSerializer.nodes,

    // 添加表格节点的序列化支持
    table(state, node) {
      console.log("序列化表格节点");
      const rows = [];
      node.forEach((row: Node) => {
        const cells = [];
        row.forEach((cell: Node) => {
          // 获取单元格内容
          let content = "";
          cell.forEach((cellChild: Node) => {
            content += cellChild.textContent || "";
          });
          if (!content.trim()) content = " ";
          cells.push(content.replace(/\|/g, "\\|"));
        });
        rows.push("| " + cells.join(" | ") + " |");
      });

      if (rows.length > 0) {
        // 添加表头分隔符
        const firstRowCells = rows[0].split("|").length - 2; // 减去开头和结尾的空元素
        const headerSeparator =
          "| " + Array(firstRowCells).fill("---").join(" | ") + " |";

        state.write(rows[0] + "\n");
        state.write(headerSeparator + "\n");
        for (let i = 1; i < rows.length; i++) {
          state.write(rows[i] + "\n");
        }
      }
      state.closeBlock(node);
    },

    table_row(state, node) {
      // 表格行的序列化由table节点统一处理
      return;
    },

    table_cell(state, node) {
      // 单元格的序列化由table节点统一处理
      return;
    },

    table_header(state, node) {
      // 表头的序列化由table节点统一处理
      return;
    }
  },

  // 继承默认的标记序列化规则
  defaultMarkdownSerializer.marks
);

console.log("创建了扩展的markdown序列化器，支持以下节点类型:");
console.log(Object.keys(markdownSerializer.nodes));

// 创建支持表格的markdown解析器
const createTableParser = (content: string): Node | null => {
  console.log("尝试解析表格内容...");

  // 简单的表格正则匹配
  const tableRegex = /\|(.+)\|/g;
  const lines = content.split("\n");
  let tableLines = [];
  let isInTable = false;

  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim();
    if (line.match(tableRegex)) {
      if (!isInTable) {
        isInTable = true;
      }
      tableLines.push(line);
    } else if (isInTable && line.match(/^\|[\s\-\|:]+\|$/)) {
      // 这是表格的分隔符行，跳过
      continue;
    } else if (isInTable && line === "") {
      // 空行，表格结束
      break;
    } else if (isInTable) {
      // 不是表格行，结束表格解析
      break;
    }
  }

  if (tableLines.length > 0) {
    console.log("发现表格，行数:", tableLines.length);

    try {
      // 解析表格数据
      const tableData = tableLines.map(line => {
        return line
          .split("|")
          .filter(cell => cell.trim() !== "")
          .map(cell => cell.trim());
      });

      if (tableData.length === 0) return null;

      console.log("表格数据:", tableData);

      // 创建表格节点
      const headerRow = tableData[0];
      const dataRows = tableData.slice(1);

      // 创建表头单元格
      const headerCells = headerRow.map(cellText =>
        schema.node("table_header", null, [
          schema.node("paragraph", null, schema.text(cellText))
        ])
      );

      // 创建数据单元格行
      const dataRowNodes = dataRows.map(row => {
        const cells = row.map(cellText =>
          schema.node("table_cell", null, [
            schema.node("paragraph", null, schema.text(cellText))
          ])
        );
        return schema.node("table_row", null, cells);
      });

      // 创建表头行
      const headerRowNode = schema.node("table_row", null, headerCells);

      // 创建完整表格
      const tableNode = schema.node("table", null, [
        headerRowNode,
        ...dataRowNodes
      ]);

      console.log("成功创建表格节点");
      return tableNode;
    } catch (error) {
      console.warn("创建表格节点失败:", error);
      return null;
    }
  }

  return null;
};

// 递归转换节点，保持内容完整性
const convertNode = (originalNode: Node, targetSchema: Schema): Node => {
  console.log(
    "转换节点:",
    originalNode.type.name,
    "内容:",
    originalNode.textContent
  );

  // 检查目标schema中是否有相同类型的节点
  const targetNodeType = targetSchema.nodes[originalNode.type.name];

  if (targetNodeType) {
    // 节点类型存在，递归转换子内容
    const convertedChildren: Node[] = [];

    if (originalNode.content) {
      originalNode.content.forEach(child => {
        const convertedChild = convertNode(child, targetSchema);
        convertedChildren.push(convertedChild);
      });
    }

    try {
      // 尝试创建相同类型的节点，保持属性和标记
      if (convertedChildren.length > 0) {
        return targetSchema.node(
          originalNode.type.name,
          originalNode.attrs || {},
          convertedChildren,
          originalNode.marks
        );
      } else if (originalNode.isText) {
        // 处理文本节点
        return targetSchema.text(originalNode.text || "", originalNode.marks);
      } else {
        // 空内容节点
        return targetSchema.node(
          originalNode.type.name,
          originalNode.attrs || {}
        );
      }
    } catch (error) {
      console.warn("创建相同类型节点失败，转换为段落:", error);
      return targetSchema.node(
        "paragraph",
        null,
        targetSchema.text(originalNode.textContent || "")
      );
    }
  } else {
    // 节点类型不存在，转换为段落（保持文本内容）
    const textContent = originalNode.textContent;
    if (textContent) {
      return targetSchema.node(
        "paragraph",
        null,
        targetSchema.text(textContent)
      );
    } else {
      // 如果没有文本内容，创建空段落
      return targetSchema.node("paragraph");
    }
  }
};

// 创建安全的文档解析函数，保持markdown内容的完整性
const parseContent = (content: string): Node => {
  try {
    console.log("=== 开始解析markdown内容 ===");
    console.log("原始内容:", content);

    // 如果内容为空，返回空段落
    if (!content || content.trim() === "") {
      console.log("内容为空，创建默认段落");
      return schema.node("doc", null, [schema.node("paragraph")]);
    }

    // 按顺序解析混合内容，支持表格和markdown交替出现
    const lines = content.split("\n");
    const contentBlocks = []; // 存储按顺序的内容块：{type: 'text'|'table', content: string}

    let currentTextLines = [];
    let currentTableLines = [];
    let isInTable = false;

    console.log("开始解析混合内容，总行数:", lines.length);

    for (let i = 0; i < lines.length; i++) {
      const line = lines[i];
      const isTableLine = line.trim().match(/^\|.*\|$/);
      const isSeparatorLine = line.trim().match(/^\|[\s\-\|:]+\|$/);

      if (isTableLine && !isSeparatorLine) {
        // 开始或继续表格
        if (!isInTable) {
          // 新表格开始，先保存之前的文本内容
          if (currentTextLines.length > 0) {
            const textContent = currentTextLines.join("\n").trim();
            if (textContent) {
              contentBlocks.push({ type: "text", content: textContent });
              console.log("保存文本块，长度:", textContent.length);
            }
            currentTextLines = [];
          }
          isInTable = true;
          currentTableLines = [];
        }
        currentTableLines.push(line);
      } else if (isSeparatorLine && isInTable) {
        // 表格分隔符，跳过
        continue;
      } else {
        // 非表格内容
        if (isInTable) {
          // 表格结束，保存表格内容
          if (currentTableLines.length > 0) {
            const tableContent = currentTableLines.join("\n");
            contentBlocks.push({ type: "table", content: tableContent });
            console.log("保存表格块，行数:", currentTableLines.length);
            currentTableLines = [];
          }
          isInTable = false;
        }
        // 添加到文本内容
        currentTextLines.push(line);
      }
    }

    // 处理剩余内容
    if (isInTable && currentTableLines.length > 0) {
      const tableContent = currentTableLines.join("\n");
      contentBlocks.push({ type: "table", content: tableContent });
      console.log("保存最后的表格块，行数:", currentTableLines.length);
    } else if (currentTextLines.length > 0) {
      const textContent = currentTextLines.join("\n").trim();
      if (textContent) {
        contentBlocks.push({ type: "text", content: textContent });
        console.log("保存最后的文本块，长度:", textContent.length);
      }
    }

    console.log("内容分离完成，总块数:", contentBlocks.length);
    console.log(
      "内容块类型:",
      contentBlocks.map(block => block.type)
    );

    // 按顺序处理所有内容块
    const allNodes: Node[] = [];

    for (let i = 0; i < contentBlocks.length; i++) {
      const block = contentBlocks[i];
      console.log(`处理第${i + 1}个块，类型: ${block.type}`);

      if (block.type === "text") {
        // 处理文本内容
        try {
          const baseDoc = defaultMarkdownParser.parse(block.content);
          if (baseDoc) {
            baseDoc.content.forEach(child => {
              const converted = convertNode(child, schema);
              allNodes.push(converted);
            });
            console.log(
              `文本块处理完成，生成节点数: ${baseDoc.content.childCount}`
            );
          }
        } catch (error) {
          console.warn("处理文本块失败:", error);
          // 作为普通段落处理
          allNodes.push(
            schema.node("paragraph", null, schema.text(block.content))
          );
        }
      } else if (block.type === "table") {
        // 处理表格内容
        const tableNode = createTableParser(block.content);
        if (tableNode) {
          allNodes.push(tableNode);
          console.log("表格块处理完成");
        } else {
          console.warn("表格解析失败，转为段落");
          allNodes.push(
            schema.node("paragraph", null, schema.text(block.content))
          );
        }
      }
    }

    // 确保至少有一个段落
    if (allNodes.length === 0) {
      console.log("没有解析出任何内容，创建包含原始文本的段落");
      allNodes.push(schema.node("paragraph", null, schema.text(content)));
    }

    const finalDoc = schema.node("doc", null, allNodes);
    console.log("=== 最终文档创建成功 ===");
    console.log("- 最终节点数:", finalDoc.content.childCount);
    console.log("- 最终文本内容:", finalDoc.textContent);
    console.log("=== 解析完成 ===");

    return finalDoc;
  } catch (error) {
    console.warn("解析markdown失败，使用纯文本段落:", error);
    // 创建包含原始内容的段落作为最终后备方案
    const paragraphNode = schema.node(
      "paragraph",
      null,
      content ? schema.text(content) : undefined
    );
    return schema.node("doc", null, [paragraphNode]);
  }
};

class ProseMirrorView {
  _content: string;
  _view: EditorView;
  constructor(target, content) {
    this._content = content;
    console.log("content", content);

    // 解析markdown内容
    const doc = parseContent(content);

    // 创建插件数组，确保表格插件正确配置
    const basePlugins = exampleSetup({ schema });
    const tablePlugins = [
      columnResizing(), // 表格列调整插件
      tableEditing() // 表格编辑插件
    ];

    // 合并所有插件
    const plugins = [...basePlugins, ...tablePlugins];

    // 创建编辑器状态
    let state = EditorState.create({
      doc,
      plugins
    });

    // 如果文档包含表格，应用表格修复
    try {
      const tr = fixTables(state);
      if (tr) {
        state = state.apply(tr);
      }
    } catch (error) {
      console.warn("表格修复失败:", error);
    }

    this._view = new EditorView(target, {
      state
    });
  }

  get content() {
    return this._content;
  }
}

class MdEditor {
  editor: ProseMirrorView;
  constructor(selector: string, content: string) {
    this.editor = new ProseMirrorView(
      document.querySelector(selector),
      content
    );
  }
}
export { MdEditor, schema, parseContent, markdownSerializer };
